<template>
  <div class="container mt-5">
    <div class="row justify-content-center">
      <div class="col-md-6">
        <div class="card">
          <div class="card-header bg-primary text-white">用户登录</div>
          <div class="card-body">
            <form @submit.prevent="handleLogin">
              <div class="mb-3">
                <label for="username" class="form-label">用户名</label>
                <input 
                  type="text" 
                  id="username" 
                  class="form-control" 
                  v-model="form.username"
                  required
                >
              </div>
              
              <div class="mb-3">
                <label for="password" class="form-label">密码</label>
                <input 
                  type="password" 
                  id="password" 
                  class="form-control" 
                  v-model="form.password"
                  required
                >
              </div>
              
              <button 
                type="submit" 
                class="btn btn-primary w-100"
                :disabled="isLoading"
              >
                {{ isLoading ? '登录中...' : '登录' }}
              </button>
              
              <div class="mt-3 text-danger" v-if="error">{{ error }}</div>
            </form>
            <!-- 新增跳转到注册页面的链接 -->
            <div class="mt-3 text-center">
              还没有账号？<router-link to="/register" class="text-primary">去注册</router-link>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'

const authStore = useAuthStore()
const router = useRouter()

const form = ref({
  username: '',
  password: ''
})

const error = ref('')
const isLoading = ref(false) 

const handleLogin = async () => {
  error.value = ''
  isLoading.value = true 

  const success = await authStore.login(
    form.value.username, 
    form.value.password
  )
  
  if (success) {
    router.push('/todo') 
  } else {
    error.value = authStore.error || '登录失败，请重试'
  }

  isLoading.value = false 
}
</script>